package beautiful.butterfly.drds.binlog.command;


import beautiful.butterfly.drds.binlog.type.CommandType;
import beautiful.butterfly.drds.binlog.utils.ByteUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FetchBinlogNamePositionCommand
{


    private String sql = null;

    public FetchBinlogNamePositionCommand(String sql)
    {
        this.sql = sql;
    }

    public void write(ChannelHandlerContext channelHandlerContext)
    {

        byte[] queryBytes = ByteUtils.writeByte((byte) CommandType.query.ordinal(), 1);
        byte[] sqlBytes = this.sql.getBytes();// 不用带\0,所以不需要使用ByteUtils
        // // 构造总的数据
        int totalCount = queryBytes.length + sqlBytes.length;
        byte[] totalCountBytes = ByteUtils.writeInt(totalCount, 3);
        byte[] commandTypeBytes = new byte[1];
        commandTypeBytes[0] = 0;// 对于fetchBinlogNamePosition命令，这里就是0
        // 可以发送了
        ByteBuf byteBuf = Unpooled.buffer(totalCount + 4);
        byteBuf.writeBytes(totalCountBytes).writeBytes(commandTypeBytes).writeBytes(queryBytes).writeBytes(sqlBytes);
        channelHandlerContext.channel().writeAndFlush(byteBuf);// 缓存清理
        log.info("send fetch binlog name&position succeed...");
    }
}
